package cn.com.qingz.modules.user.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.http.cookie.Cookie;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.miemiedev.mybatis.paginator.domain.PageList;

import cn.com.qingz.core.constantes.SystemConstantes;
import cn.com.qingz.core.exception.DicmfException;
import cn.com.qingz.core.model.DefaultResp;
import cn.com.qingz.core.utils.AliSMSUtils;
import cn.com.qingz.core.utils.DateUtils;
import cn.com.qingz.core.utils.RandomCodeUtils;
import cn.com.qingz.core.utils.ShortUUID;
import cn.com.qingz.modules.user.model.Customer;
import cn.com.qingz.modules.user.model.Design;
import cn.com.qingz.modules.user.model.DesignCase;
import cn.com.qingz.modules.user.model.SMSCode;
import cn.com.qingz.modules.user.service.CustomerService;
import cn.com.qingz.modules.user.vo.CustomerSearchCondition;

/**
 * @author codeGen
 */
@Controller
@RequestMapping("customer/*")
public class CustomerController {

    @Resource
    private CustomerService customerService;

    @RequestMapping("isLogin")
    @ResponseBody
    public Map<String, Object> isLogin(HttpServletRequest request) {
        Map<String, Object> res = new HashMap<>();
        Customer customer = (Customer) request.getSession().getAttribute("login_user");
        if (customer == null) {
            res.put("code", "fail");
            return res;
        }
        res.put("data", customer);
        res.put("code", "success");
        return res;
    }

    /**
     * 查用户的 3d设计数据
     * @param request
     * @return
     */
    @RequestMapping("queryUserDesings")
    @ResponseBody
    public Map<String, Object> queryUserDesings(HttpServletRequest request, Integer userid) {
        Map<String, Object> res = new HashMap<>();
        List<Map<String, Object>> data = customerService.getUserDesign(userid);
        if (CollectionUtils.isEmpty(data)) {
            res.put("total", 0);
        } else {
            res.put("total", data.size());
        }
        res.put("data", data);
        return res;
    }

    /**
     * 查询户型图
     * @param keyword 关键字
     * @return
     */
    @RequestMapping("queryHouseModel")
    @ResponseBody
    public Map<String, Object> queryHouseModel(String keyword, @RequestParam(required = false, defaultValue = "0") int page,
            @RequestParam(required = false, defaultValue = "10") int limit) {
        Map<String, Object> res = new HashMap<String, Object>();
        PageList<Design> list = customerService.queryHouseModelByPage(keyword, page, limit);
        res.put("total", list.getPaginator().getTotalCount());
        int total = list.getPaginator().getTotalCount();
        int totalpage = 0;
        if (total % limit == 0) {
            totalpage = total / limit;
        } else {
            totalpage = (total / limit) + 1;
        }
        res.put("totalpage", totalpage);
        res.put("rows", list);
        return res;
    }

    /**
     * 注册用户
     * @param
     * @return
     */
    @RequestMapping("save")
    @ResponseBody
    public DefaultResp<String> save(HttpServletRequest request, Customer entity, String inputCode, String smsCode) {
        CustomerController.ValidCode vc = (CustomerController.ValidCode) request.getSession().getAttribute(entity.getPhone());
        if (vc == null) {
            throw new DicmfException(SystemConstantes.ERROR, "短信验证码校验失败");
        } else {
            if (!vc.getCode().equals(smsCode)) {
                throw new DicmfException(SystemConstantes.ERROR, "短信验证码校验失败");
            }
        }

        boolean b = RandomCodeUtils.checkRandomCode(request, inputCode);
        if (!b) {
            throw new DicmfException(SystemConstantes.ERROR, "验证码输入错误!");
        }
        DefaultResp<String> res = new DefaultResp<String>();
        customerService.doAddOrUpdate(entity);
        return res;
    }

    /**
     * 用户登录
     * @param request
     * @param entity
     * @param inputCode
     * @return
     */
    @RequestMapping("login")
    @ResponseBody
    public DefaultResp<Map<String, Object>> login(HttpServletRequest request, Customer entity, String inputCode) {
        boolean b = RandomCodeUtils.checkRandomCode(request, inputCode);
        if (!b) {
            throw new DicmfException(SystemConstantes.ERROR, "验证码输入错误!");
        }
        javax.servlet.http.Cookie[] cookies = request.getCookies();
        for (javax.servlet.http.Cookie cookie : cookies) {
            cookie.getName().equals("");
        }
        DefaultResp<Map<String, Object>> res = new DefaultResp<>();
        Customer customer = customerService.doLogin(entity.getPhone(), entity.getPassword(), request);
        Map<String, Object> data = new HashMap<>();
        data.put("token", customer.getToken());
        data.put("userid", customer.getCustomerid().toString());
        res.setData(data);

        return res;
    }

    /**
     * 点击查看用户详细信息
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("goDesigner")
    public String goDesigner(HttpServletRequest request, Integer id) {
        Customer customer = customerService.get(id);
        request.setAttribute("customer", customer);
        request.setAttribute("list", customer.getCaselist());
        return "designerInfo";
    }

    @RequestMapping("goDesignerDetail")
    public String goDesignerDetail(HttpServletRequest request, Integer id) {
        Customer customer = customerService.get(id);
        request.setAttribute("customer", customer);
        request.setAttribute("list", customer.getCaselist());
        return "view/personDetail";
    }

    @RequestMapping("getCustomerById")
    @ResponseBody
    public DefaultResp<Customer> getCustomerById(HttpServletRequest request, Integer id) {
        DefaultResp<Customer> res = new DefaultResp<Customer>();
        Customer customer = customerService.get(id);
        res.setData(customer);
        return res;
    }

    /**
     * 进入个人中心编辑
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("goPersonCenter")
    public String goPersonCenter(HttpServletRequest request, Integer id) {
        Customer customer = customerService.get(id);
        request.setAttribute("currentUser", customer);
        request.setAttribute("list", customer.getCaselist());

        request.setAttribute("listJSON", JSON.toJSONString(customer.getCaselist()));

        return "personCenter";
    }

    /**
     * 保存个人中心基本信息
     * @param request
     * @param entity
     * @param response
     * @return
     */
    @RequestMapping("saveProfile")
    @ResponseBody
    public DefaultResp<String> saveProfile(HttpServletRequest request, Customer entity, HttpServletResponse response) {
        response.setContentType("text/plain;charset=UTF-8");
        DefaultResp<String> res = new DefaultResp<String>();
        customerService.doUpdate(entity);
        return res;
    }

    @RequestMapping("saveDesignCase")
    @ResponseBody
    public DefaultResp<String> saveDesignCase(HttpServletRequest request, DesignCase dc, HttpServletResponse response) {
        response.setContentType("text/plain;charset=UTF-8");
        DefaultResp<String> res = new DefaultResp<String>();
        customerService.doSaveDesignCase(dc);
        return res;
    }

    @RequestMapping("authCustomer")
    //	@ResponseBody
    public void authCustomer(HttpServletRequest request, String json, HttpServletResponse response) throws IOException {
        DefaultResp<String> res = new DefaultResp<String>();
        List<DesignCase> list = JSON.parseArray(json, DesignCase.class);
        customerService.doAuth(list);
        response.getOutputStream().write(JSON.toJSONString(res).getBytes());
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    /**
     * 认证通过 (发送邮件通知)
     * @param request
     * @param id
     * @throws IOException
     */
    @RequestMapping("doEx")
    @ResponseBody
    public DefaultResp<String> doEx(HttpServletRequest request, Integer id) throws IOException {
        DefaultResp<String> res = new DefaultResp<String>();
        customerService.doEx(id);
        return res;
    }

    /**
     * 生成验证码
     * @param request
     * @param resp
     */
    @RequestMapping("createRandomCode")
    public void createRandomCode(HttpServletRequest request, HttpServletResponse resp) {
        RandomCodeUtils.removeRandomCode(request);
        RandomCodeUtils.createRandomCode(request, resp);
    }

    /**
     * 分页查询
     * @param condition
     * @param page 页码
     * @return rows 每页行数
     */
    @RequestMapping("queryForPage")
    @ResponseBody
    public Map<String, Object> queryByPage(CustomerSearchCondition condition, @RequestParam(required = false, defaultValue = "0") int page,
            @RequestParam(required = false, defaultValue = "10") int rows) {
        PageList<?> list = customerService.queryForPage(condition, page, rows);
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("total", list.getPaginator().getTotalCount());
        int total = list.getPaginator().getTotalCount();
        int totalpage = 0;
        if (total % rows == 0) {
            totalpage = total / rows;
        } else {
            totalpage = (total / rows) + 1;
        }
        res.put("totalpage", totalpage);
        res.put("rows", list);
        return res;
    }

    /**
     * 分页查询案例
     * @param condition
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping("queryCasePage")
    @ResponseBody
    public Map<String, Object> queryCasePage(CustomerSearchCondition condition, @RequestParam(required = false, defaultValue = "0") int page,
            @RequestParam(required = false, defaultValue = "10") int rows) {
        PageList<?> list = customerService.queryDesignPage(condition, page, rows);
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("total", list.getPaginator().getTotalCount());
        int total = list.getPaginator().getTotalCount();
        int totalpage = 0;
        if (total % rows == 0) {
            totalpage = total / rows;
        } else {
            totalpage = (total / rows) + 1;
        }
        res.put("totalpage", totalpage);
        res.put("rows", list);
        return res;
    }

    /**
     * 前台查询
     * @param condition
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping("webQueryForPage")
    @ResponseBody
    public Map<String, Object> webQueryForPage(CustomerSearchCondition condition, @RequestParam(required = false, defaultValue = "0") int page,
            @RequestParam(required = false, defaultValue = "10") int rows) {
        PageList<Customer> list = customerService.queryForPage(condition, page, rows);
        Map<String, Object> res = new HashMap<>();
        res.put("total", list.getPaginator().getTotalCount());
        res.put("rows", list);
        return res;
    }

    private ThreadLocal<Map<String, SMSCode>> codelist;

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @RequestMapping("sendSMSValidCode")
    @ResponseBody
    public String sendSMSValidCode(String phone, HttpServletRequest request) {
        String code = ShortUUID.get6Number() + "";
        try {
            AliSMSUtils.sendValidCode(phone, code, "Lphome");
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
        request.getSession().setAttribute(phone, new ValidCode(code, new Date()));
        return "success";
    }

    public class ValidCode {
        private String code;

        private Date time;

        public ValidCode(String code, Date time) {
            this.code = code;
            this.time = time;
        }

        public boolean istimeout() {
            int s = DateUtils.sBetween(time, new Date());
            return s > 60;
        }

        public String getCode() {
            return this.code;
        }
    }

}